package sandbox.vaadin.skiller.entity;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;

import org.apache.log4j.Logger;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import sandbox.vaadin.skiller.entity.Skillgroup;
import sandbox.vaadin.skiller.entity.Populator.SKILLGROUP;

public class JUTSkillgroup
{
	private static final Logger LOGGER = Logger.getLogger(Populator.class);

	private static EntityManagerFactory EMF;
	private static EntityManager EM;

	private EntityTransaction tx;

	@BeforeClass
	public static void beforeClass()
	{
		EMF = Persistence.createEntityManagerFactory("jpa");
		EM = EMF.createEntityManager();
	}

	@AfterClass
	public static void afterClass()
	{
		EM.close();
		EMF.close();
	}

	@Before
	public void before()
	{
		tx = EM.getTransaction();
		tx.begin();
		UnPopulator unPopulator = new UnPopulator(EM);
		unPopulator.unpopulate();
		Populator populator = new Populator(EM);
		populator.populate();
		tx.commit();
	}

	@Test
	public void testQuerySkillgroup()
	{
		assertNotNull("querySkillgroup is null", querySkillgroup());
	}

	@Test
	public void testQuerySkillgroupChildren()
	{
		int size = querySkillgroupChildren(querySkillgroup()).size();
		assertEquals("unexpected size of skillgroup children", 3, size);
	}

	private Skillgroup querySkillgroup()
	{
		TypedQuery<Skillgroup> q =
				EM.createNamedQuery("Skillgroup_by_name", Skillgroup.class);
		q.setParameter("name", SKILLGROUP.MethodicalCompetence.getName());
		Skillgroup result = q.getSingleResult();
		LOGGER.debug("found skillgroup " + result.getName());
		return result;
	}

	private List<Skillgroup> querySkillgroupChildren(Skillgroup skillgroup)
	{
		TypedQuery<Skillgroup> q =
				EM.createNamedQuery("Skillgroup_select_children", Skillgroup.class);
		q.setParameter("parent", skillgroup);
		List<Skillgroup> result = q.getResultList();
		LOGGER.debug("found " + result.size() + " children for skillgroup " + skillgroup.getName());
		return result;
	}
}